package cn.laixueit.service.impl;

import cn.laixueit.mapper.ClassInfoMapper;
import cn.laixueit.pojo.ClassInfo;
import cn.laixueit.pojo.ClassInfoExample;
import cn.laixueit.service.ClassService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Override
    public List<ClassInfo> selectall() {
        return classInfoMapper.selectByExample(null);
    }

    @Override
    public void save(ClassInfo classInfo) {
        ClassInfoExample example = getContion(classInfo);
        List<ClassInfo> list = classInfoMapper.selectByExample(example);
        if(list.size()==0){
            classInfo.setOpendate(new Date());
            classInfoMapper.insertSelective(classInfo);
            return;
        }
        throw  new RuntimeException("班级已存在");
    }

    @Override
    public PageInfo<ClassInfo> findall(Integer startpage, Integer pagesize,ClassInfo classInfo) {
        PageHelper.startPage(startpage,pagesize);
        ClassInfoExample example = getContion(classInfo);
        List<ClassInfo> classList =  classInfoMapper.selectByExample(example);
        PageInfo<ClassInfo> pageInfo = new PageInfo<>(classList);
        return pageInfo;
    }

    private ClassInfoExample getContion(ClassInfo classInfo) {
        ClassInfoExample example = new ClassInfoExample();
        example.setOrderByClause("openDate desc");
        if(classInfo!=null){
            ClassInfoExample.Criteria criteria = example.createCriteria();
            if(classInfo.getId()!=null && classInfo.getId() !=0){
                criteria.andIdEqualTo(classInfo.getId());
            }
            if(classInfo.getOpendate()!=null){
                criteria.andOpendateGreaterThanOrEqualTo(classInfo.getOpendate());
            }
            if(classInfo.getClassname()!=null && classInfo.getClassname()!=""){
                criteria.andClassnameEqualTo(classInfo.getClassname());
            }
        }
        return example;
    }


}
